package tongwentongshu.com.app.presenter;

import android.content.Context;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendAllowType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMManager;
import com.umeng.message.PushAgent;

import java.util.Map;

import tencent.tls.platform.TLSLoginHelper;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.activity.LoginActivity;
import tongwentongshu.com.app.activityim.HomeActivity;
import tongwentongshu.com.app.activityim.UserInfo;
import tongwentongshu.com.app.bean.LoginUser;
import tongwentongshu.com.app.contract.LoginContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.db.DataKeeper;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.update.UpdateFractory;
import tongwentongshu.com.app.utils.SpUtils;

/**
 * Created by XiongBin on 2017/7/11.
 */

public class LoginPresenter implements LoginContract.Presenter {
    private LoginContract.View loginView;
    private Map<String, String> map;

    public LoginPresenter(LoginContract.View loginView) {
        this.loginView = loginView;
    }

    @Override
    public void login(final Context mContext) {
        String tokenD = PushAgent.getInstance(mContext).getRegistrationId();
        final String phone = loginView.getPhone();
        final String password = loginView.getPw();
        if (TextUtils.isEmpty(phone)) {
            loginView.onShowError("手机号不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            loginView.onShowError("密码不能为空");
            return;
        }
        map = new ArrayMap<>();
        map.put("mobile", phone);
        map.put("password", password);
        map.put("phoneType", "0");
        map.put("device_tokens", tokenD);
        map.put("longitude", SpUtils.getString(mContext, Cache.LON, ""));
        map.put("latitude", SpUtils.getString(mContext, Cache.LAT, ""));
        map.put("mapaddress", SpUtils.getString(mContext, Cache.ADDRESS, ""));
        UpdateFractory.getBuild()
                .name("LoginCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<LoginUser>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(LoginUser login, String msg) {
                        Log.e("LoginUser", msg.toString());
                        if (null != login) {
                            SpUtils.setString(mContext, Cache.USER_NAME, phone);
                            SpUtils.setString(mContext, Cache.USER_PASSWORD, password);
                            login.setLogin(true);
                            DataKeeper.keepSerializable(App.getContext(), login);
                            Cache.setUser();

                            UserInfo.getInstance().setUserSig(login.getData().getSig());
//                            if (!TextUtils.isEmpty(UserInfo.getInstance().getId()))
                            initMSG(mContext, login);
//                            setAddType();
                        }
                        loginView.onSuccess(msg);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    void initMSG(Context mContext, final LoginUser login) {
        TLSLoginHelper loginHelper = TLSLoginHelper.getInstance().init(mContext,
                1400036219, 14371, SpUtils.getString(mContext, Cache.USER_NAME, ""));

//        loginHelper.setTimeOut(TLSConfiguration.TIMEOUT);
//        loginHelper.setLocalId(TLSConfiguration.LANGUAGE_CODE);
        loginHelper.setTestHost("", true);                   // 走sso
        final String identify = SpUtils.getString(mContext, Cache.USER_NAME, "");
        final String userSig = login.getData().getSig();
        TIMManager.getInstance().login(identify, userSig, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.d("shiqiang", "login failed. code: " + code + " errmsg: " + desc);
                System.out.println("wocBUGkle");
            }

            @Override
            public void onSuccess() {
                Log.d("shiqiang", "login succ");
                System.out.println("wochenggongkle");


                UserInfo.getInstance().setId(identify);
                UserInfo.getInstance().setUserSig(userSig);

                setAddType(login);

            }
        });
    }

    private void setAddType(LoginUser login) {
        //设置自己的好友验证方式为b不需要验证
        TIMFriendshipManager.ModifyUserProfileParam param = new TIMFriendshipManager.ModifyUserProfileParam();
        param.setAllowType(TIMFriendAllowType.TIM_FRIEND_ALLOW_ANY);
        param.setNickname(login.getData().getNickname());
        param.setFaceUrl(login.getData().getHeadurl());
        TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.e("LoginPresenter", "modifyProfile failed: " + code + " desc" + desc);
            }

            @Override
            public void onSuccess() {
                Log.e("TIMFriendshipManager", "设置昵称头像成功！");
            }
        });
    }
}